package com.hps.boot.seata.config;

import com.hps.boot.seata.interceptor.SeataRestTemplateInterceptor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;

/**
 *
 * @author heps
 * @since 2020/9/27
 */
@Configuration
public class SeataRestTemplateAutoConfiguration {

  @Autowired(required = false)
  private Collection<RestTemplate> restTemplates;

  @Autowired
  private SeataRestTemplateInterceptor seataRestTemplateInterceptor;

  public SeataRestTemplateAutoConfiguration() {
  }

  @Bean
  public SeataRestTemplateInterceptor seataRestTemplateInterceptor() {
    return new SeataRestTemplateInterceptor();
  }

  @PostConstruct
  public void init() {
    if (this.restTemplates != null) {
      Iterator<RestTemplate> it = this.restTemplates.iterator();

      while (it.hasNext()) {
        RestTemplate restTemplate = it.next();
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList(restTemplate.getInterceptors());
        interceptors.add(this.seataRestTemplateInterceptor);
        restTemplate.setInterceptors(interceptors);
      }
    }

  }
}
